﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SalePromotion.Extensions;
using SalePromotion.Models;
using SalePromotion.Pagination;
using SalePromotion.Service;
using eBay.Service.Core.Sdk;
using eBay.Service.Core.Soap;

namespace SalePromotion.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index(int page = 1, FilterBy filter = FilterBy.All)
        {


            if (!HttpContext.User.Identity.IsAuthenticated)
            {
                return RedirectToAction("logon", "Account");
            }

            if (!HttpContext.User.Identity.Name.IsTokenFetched())
            {
                return RedirectToAction("FetchToken", "Account", new LogOnModel
                {
                    IsActive = false,
                    UserName = HttpContext.User.Identity.Name
                });
            }
            var service = new SaleDiscountService();
            var criteria = new SaleDiscountCriteria() { Filter = filter };
            var pagination = new PaginationOptions(20, page);
            var items = new SaleDiscountService().SearchSaleByCondition(pagination, criteria).Select(item => new SaleModel(item)).Where(item => FilterSaleBy(item, criteria));

            var totalItems = service.GetSaleCount(criteria);

            var pagedList = new PagedList<SaleModel>(items, totalItems, pagination);

            return View(new SalePaginationListModel
            {
                PagedItems = pagedList,
                Filter = filter,
            });

        }


        public ActionResult SaleEdit(int? id = null, bool fromSession =false)
        {

            if (!HttpContext.User.Identity.IsAuthenticated)
            {
                return RedirectToAction("logon", "Account");
            }

            if (!HttpContext.User.Identity.Name.IsTokenFetched())
            {
                return RedirectToAction("FetchToken", "Account", new LogOnModel
                {
                    IsActive = false,
                    UserName = HttpContext.User.Identity.Name
                });
            }
            var service = new SaleDiscountService();
            var model = new SaleModel();
            var isEditModel = id.HasValue && id > 0;
            if (isEditModel)
            {
                model = new SaleModel(service.GetSale(id.Value));
            }
            var saleModelFromSession = TempData["SalePromotion"] as SaleModel;
            if (saleModelFromSession != null && fromSession)
            {
                model.RestoreFromSession(saleModelFromSession);
            }
            return View("SaleEdit", model);
        }

        [HttpPost]
        public ActionResult SaleEdit(SaleModel model, FormCollection collection)
        {

            if (!HttpContext.User.Identity.IsAuthenticated)
            {
                return RedirectToAction("logon", "Account");
            }

            if (!HttpContext.User.Identity.Name.IsTokenFetched())
            {
                return RedirectToAction("FetchToken", "Account", new LogOnModel
                {
                    IsActive = false,
                    UserName = HttpContext.User.Identity.Name
                });
            }

            var isChooseListing = collection.AllKeys.Contains("Cancel");
            var message = CreateSale(model, collection, !isChooseListing);
            if (isChooseListing)
            {
                TempData["SalePromotion"] = model;
                return RedirectToAction("ChooseListing", new { model.Id });
            }
            if (!string.IsNullOrWhiteSpace(message))
            {
                HttpContext.Response.Cookies.Add(new HttpCookie("Flash.Error", message) { Path = "/" });
                return View("SaleEdit", model);
            }
            return RedirectToAction("Index");
        }
        [HttpPost]
        public ActionResult DeleteSalePromotion(int id, int page = 1, FilterBy filter = FilterBy.All)
        {
            try
            {
                var service = new SaleDiscountService();
                service.RemoveSaleDiscount(id);

                return RedirectToAction("Index", new { page, filter })
                    .Success("Your Sales was successfully deleted");
            }
            catch (SdkException e)
            {
                return RedirectToAction("Index", new { page, filter })
                   .Error(e.Message);


            }
        }


        public ActionResult ChooseListing(int? id)
        {
            if (!HttpContext.User.Identity.IsAuthenticated)
            {
                return RedirectToAction("logon", "Account");
            }

            if (!HttpContext.User.Identity.Name.IsTokenFetched())
            {
                return RedirectToAction("FetchToken", "Account", new LogOnModel
                {
                    IsActive = false,
                    UserName = HttpContext.User.Identity.Name
                });
            }

            return ChooseListing(new EBayListingModel() { Id = id, SortBy = ItemSortTypeCodeType.EndTime.ToString(), ListingFormat = ListingTypeCodeType.FixedPriceItem.ToString() });
        }

        [HttpPost]
        public ActionResult ChooseListing(EBayListingModel model)
        {
            var service = new SaleDiscountService();
            var allListings = service.LoadActiveListings(new ItemInfoCriteria { SortBy = model.SortBy, ItemFormat = model.ListingFormat }, false);
            var existingListings = new List<SaleListing>();
            if (model.Id.HasValue)
                existingListings = service.GetSaleListings(model.Id.Value).ToList();
            var newModel = model;
            newModel.EBayListings = allListings.Select(listing => new ItemInfoModel(listing, existingListings));
            TempData["SalePromotion"] = TempData["SalePromotion"];
            //return new JsonResult()
            //           {

            //           };
            return View(newModel);
        }

        [HttpPost]
        public ActionResult ConfirmChooseListing(int? id, FormCollection collection)
        {
            var isSelectedArray = collection["item.IsSelected"].Replace("false,true", "true").Split(new char[] { ',' });
            var itemIds = collection["item.ItemId"].Split(new char[] { ',' });
            var selectedItemIds = new List<string>();
            for (int i = 0; i < isSelectedArray.Length; i++)
            {
                if (Convert.ToBoolean(isSelectedArray[i]))
                {
                    selectedItemIds.Add(itemIds[i]);
                }
            }
            var currentSalePromotion = TempData["SalePromotion"] as SaleModel;
            if (currentSalePromotion != null)
            {
                if (selectedItemIds.Count > 0)
                {

                    currentSalePromotion.SelectedListingArray = selectedItemIds;
                }


            }
            TempData["SalePromotion"] = currentSalePromotion;
            return RedirectToAction("SaleEdit", new { id, fromSession =true});
        }

        public ActionResult About()
        {
            return View();
        }

        private bool FilterSaleBy(SaleModel model, SaleDiscountCriteria criteria)
        {
            if (criteria.Filter == Service.FilterBy.All) return true;
            return criteria.Filter.ToString() == model.StatusText;
        }

        private string CreateSale(SaleModel model, FormCollection collection, bool save = true)
        {
            try
            {
                var service = new SaleDiscountService();
                Sale entity = null;
                if (model.Id.HasValue && model.Id > 0)
                {
                    entity = service.GetSale(model.Id.Value);

                }
                else
                {
                    entity = new Sale();

                }
                entity.eBayUserTokenId = service.GetEbayUserToken(HttpContext.User.Identity.Name).Id;
                entity.SaleName = model.SaleName??string.Empty;

                DateTime? dateStart = null, dateEnd = null;
                dateStart = model.StartDateDate.AddHours(double.Parse(model.StartDateHour)).AddMinutes(double.Parse(model.StartDateMinute));
                dateEnd = model.EndDateDate.AddHours(double.Parse(model.EndDateHour)).AddMinutes(double.Parse(model.EndDateMinute));
                entity.StartDate = dateStart.Value;
                entity.EndDate = dateEnd.Value;
                entity.IsAuctionExcluded = model.IsAuctionExcluded;
                entity.DiscountType = (short)model.DiscountType;
                if ((entity.DiscountType) == (int)DiscountCodeType.Price)
                {
                    entity.DiscountRatio = model.DiscountRatioFixed;
                }
                else
                {
                    entity.DiscountRatio = model.DiscountRatioByPercent;
                }

                entity.IsFreeShipping = model.IsFreeShipping;
                entity.AllAuctionItems = model.AllAuctionItems;
                entity.AllFixedPriceItems = model.AllFixedPriceItems;
                entity.AllStoreInventoryItems = model.AllStoreInventoryItems;
                entity.StoreCatetoryID = model.StoreCategoryId;
                entity.CreatedDate = entity.UpdatedDate = DateTime.Now;

                if (save)
                {
                    service.CreateOrUpdateSale(entity, model.SelectedListings);
                }

            }
            catch (SdkException e)
            {
                return e.Message;
            }

            catch (Exception e)
            {
                throw;
            }
            return string.Empty;

        }

    }
}
